<template>
  <div class="page-wrapper">
    <div class="header-wrapper">
      <h2 class="top">
        <van-icon class="back-icon" @click="fanhui" name="arrow-left" size="30px" />
        <span class="title-text">随访服务记录</span>
      </h2>
    </div>
    <!-- 添加 v-if 判断数据是否加载完成 -->
    <div v-if="!isLoading">
      <!-- 使用 v-for 指令循环渲染医生信息 -->
      <div class="hezi-1" v-for="doctor in doctors" :key="doctor.id" @click="jinqu(doctor.status, doctor.serviceRecordId)">
        <div class="tu-p">
          <!-- 根据 doctor.status 的值设置不同的字体颜色 -->
          <span :style="{ color: getStatusColor(doctor.status) }">{{doctor.status}}</span>
        </div>
        <div class="tu-pian1">
          <span style="font-weight: bold">{{doctor.doctorName}}医生&emsp;</span>
          <!-- 根据 doctor.serviceLocation 的值显示不同样式的按钮 -->
          <el-button v-if="doctor.serviceLocation === '机构门诊'" type="danger" plain>{{doctor.serviceLocation}}</el-button>
          <el-button v-else-if="doctor.serviceLocation === '患者家中'" type="warning" plain>{{doctor.serviceLocation}}</el-button>
          <!-- 可以添加默认情况，当 serviceLocation 不是上述两种值时显示 -->
          <el-button v-else type="default" plain style="border-radius: 30px">{{doctor.serviceLocation}}</el-button>
          <br><span style="font-size: 15px;color: #AAAAAC">服务时间：{{formatServiceTime(doctor.serviceTime)}}</span>
          <!-- 添加条件判断，如果 value 不为 null 则显示服务评价 -->
          <br><span v-if="doctor.effectScore!== null" style="font-size: 15px;color: #AAAAAC">服务评价：<van-rate color="#FDDB78"
                                                                                                                v-model="doctor.effectScore"
                                                                                                                allow-half
                                                                                                                void-icon="star"
                                                                                                                void-color="#eee"
        /><span style="color: #FDDB78; font-size: 20px" >&emsp;{{doctor.effectScore}}</span></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      doctors: [], // 修改为 doctors 数组
      isLoading: true, // 数据加载状态
      serviceItem:''
    };
  },
  methods: {
    findAll() {
      this.isLoading = true; // 开始加载数据
      console.log('用户ID:', this.serviceItem)
      if (this.serviceItem==null){
          this.findServiceRecordAll()
      }else {
        this.findServiceRecordByUserId()
      }
    },
    findServiceRecordAll(){
      this.axios.get(`http://localhost:10086/api/service/service_record/findServiceRecordByUserId`)
          .then(res => {
            console.log('请求响应:', res);
            console.log('完整返回数据:', res.data.data);
            if (res.data.code === 200 && res.data.data) {
              this.doctors = res.data.data;
              // 处理 serviceTime，去掉 T
              this.doctors.forEach(doctor => {
                if (doctor.serviceTime) {
                  doctor.serviceTime = doctor.serviceTime.replace('T', ' ');
                }
              });
              console.log('医生数据:', this.doctors);
            } else {
              this.$message.error("获取失败");
            }
          })
          .catch(error => {
            console.error('请求出错:', error);
            this.$message.error('网络请求出错，请检查网络或服务器状态');
          })
          .finally(() => {
            this.isLoading = false; // 数据加载完成
          });
    },
    findServiceRecordByUserId(){
      this.axios.get(`http://localhost:10086/api/service/service_record/findServiceRecordByUserId/${this.serviceItem}`)
          .then(res => {
            console.log('请求响应:', res);
            console.log('完整返回数据:', res.data.data);
            if (res.data.code === 200 && res.data.data) {
              this.doctors = res.data.data;
              // 处理 serviceTime，去掉 T
              this.doctors.forEach(doctor => {
                if (doctor.serviceTime) {
                  doctor.serviceTime = doctor.serviceTime.replace('T', ' ');
                }
              });
              console.log('医生数据:', this.doctors);
            } else {
              this.$message.error("获取失败");
            }
          })
          .catch(error => {
            console.error('请求出错:', error);
            this.$message.error('网络请求出错，请检查网络或服务器状态');
          })
          .finally(() => {
            this.isLoading = false; // 数据加载完成
          });
    },
    fanhui() {
      localStorage.removeItem("itemName")
      this.$router.go(-1)
    },
    jinqu(status, serviceRecordId) {
      localStorage.setItem("serviceRecordId", JSON.stringify(serviceRecordId));
      localStorage.setItem("status", JSON.stringify(status));
      console.log("serviceRecordId:"+serviceRecordId)
      console.log("status:"+status)
      let path;
      if (status === '已完成') {
        path = '/serviceDetail1';
      } else if (status === '待审核' || status === '审核通过') {
        path = '/serviceDetail2';
      } else {
        path = '/serviceDetail3';
      }
      this.$router.push({
        path: path,
        query: {
          status: status,
          id: serviceRecordId
        }
      });
    },
    // 根据状态返回对应的颜色
    getStatusColor(status) {
      switch (status) {
        case '已完成':
          return 'black';
        case '待审核':
          return '#46D5B2';
        case '审核通过':
          return '#FDE07B';
        case '申请失败':
          return '#FA8C85';
        default:
          return 'black';
      }
    },
    // 格式化服务时间，可根据需要扩展更多功能
    formatServiceTime(time) {
      return time ? time.replace('T', ' ') : '';
    }
  },
  created() {
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({ name: 'login' });
      }, 1000);
    }
    // 设置全局默认请求头
    this.axios.defaults.headers.common['token'] = token;
    this.serviceItem = this.$route.query.itemName;
    if (this.serviceItem==null){
      this.serviceItem = localStorage.getItem('itemName');
    }
    console.log("111"+this.serviceItem)
    this.findAll();

  }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.tu-pian1 {
  width: 80%;
  height: 80px;
  margin-left: 10%;
  float: left;
  margin-top: 10px;
}

.tu-p {
  width: 80%;
  height: 30px;
  margin-top: 10px;
  margin-left: 10%;
  float: left;
  border-bottom: black solid 1px;
}

.hezi-1 {
  width: 80%;
  height: 150px;
  background-color: white;
  margin-top: 20px;
  margin-left: 10%;
  border-radius: 15px;
}

.tu-pian1 img {
  width: 80px;
  height: 80px;
  border-radius: 20px;
}

.tu-pian img {
  width: 150px;
  height: 150px;
  float: left;
  border-radius: 30px;
  box-shadow: 0 0 10px rgba(0, 128, 255, 0.2);
}

.page-wrapper {
  min-height: 100vh;
  background-color: #F5F9FD;
}

.header-wrapper {
  background-color: white;
}

.top {
  display: flex;
  align-items: center;
  height: 50px;
  position: relative;
}

.back-icon {
  position: absolute;
  left: 10px;
}

.title-text {
  width: 100%;
  text-align: center;
}

img {
  /*background-color: red;*/
  width: 100%;
  height: 100%;
}

.loading {
  text-align: center;
  margin-top: 20px;
  color: #999;
}

.no-data {
  text-align: center;
  margin-top: 20px;
  color: #999;
}
</style>